package web.handler

import event.DeliveryTaskEvent
import event.RemoteDelivery
import event.motor.DeliveryChangedEvent
import ext.log
import manager.DeliveryManager
import manager.WaresManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import web.request.jsonOf

class OnDeliveryHandler(json: JSONObject) : AbstractHandler(json, REQ) {

    companion object {

        const val REQ = "delivery"

        const val FIELD_WARES_ID = "waresId"
        const val FIELD_HOT = "hot"

        const val MSG_FAIL = "fail"
        const val MSG_SUCC = "success"
        const val MSG_COMPLETE = "complete"

        var runFlag = false
            private set

    }

    override fun exec(): JSONObject {

        if (runFlag) {
            throw IllegalStateException("Delivery has started")
        }

        start()
        runFlag = true
        val waresId = json.getString(FIELD_WARES_ID)
        val hot = json.getBoolean(FIELD_HOT)

        log("出货:$waresId $hot")

        WaresManager.setIndexByWaresId(waresId)

        EventBus.getDefault().post(RemoteDelivery())

        //   val wc = WaresManager.findByWaresId(waresId)
        //  TaskManager.AsyncHandler.post(DeliveryTask(wc, hot))

        return jsonOf("Start delivery", CODE_OK)
    }

    private fun start() {
        EventBus.getDefault().register(this)
    }

    private fun complete() {
        EventBus.getDefault().unregister(this)
        sendResponse(jsonOf(MSG_COMPLETE, CODE_OK))
        runFlag = false
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onDeliveryTaskEvent(env: DeliveryTaskEvent) {
        if (env.cargo != null) {
            return
        }

        val resp = jsonOf(MSG_FAIL, 1)
        sendResponse(resp)
        complete()
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onDeliveryChangedEvent(env: DeliveryChangedEvent) {
        when (env.state) {

            DeliveryChangedEvent.Preheat -> { sendResponse(jsonOf("preheat", CODE_OK))
            }

            DeliveryChangedEvent.Heat -> { sendResponse(jsonOf("heat", CODE_OK))
            }

            DeliveryChangedEvent.Deliver -> { sendResponse(jsonOf("push", CODE_OK))
            }

            DeliveryChangedEvent.Success -> {
                DeliveryManager.isSuccess = true
                sendResponse(jsonOf(MSG_SUCC, CODE_OK))
            }

            DeliveryChangedEvent.Error -> {
                sendResponse(jsonOf(MSG_FAIL, 1))
                complete()
            }

            DeliveryChangedEvent.Complete -> { complete()
            }

            else -> {
                if (DeliveryManager.isSuccess) {
                    complete()
                }
            }
        }
    }

}


















